package com.lagou.edu.controller;

import com.alibaba.druid.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {
    public static final String USER_PASSWORD = "admin";
    public static final String USER_NAME = "admin";
    @RequestMapping(value = "login.do",method = {RequestMethod.POST,RequestMethod.GET})
    public String login(@RequestParam("userName") String userName, @RequestParam("userPassword") String userPassword
            ,HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        if (StringUtils.equals(userName,USER_NAME)&& StringUtils.equals(userPassword,USER_PASSWORD) ){
            addCookie(userName,userPassword,httpServletResponse);
            return "forward:resumes";
        }
        delCookie(httpServletRequest,httpServletResponse,userName);
        return "login";
    }

    //创建cookie，并将新cookie添加到“响应对象”response中。
    public void addCookie(String userName, String userPassword,HttpServletResponse response){

        Cookie cookie = new Cookie(userName,userPassword);//创建新cookie
        cookie.setMaxAge(5 * 60*60);// 设置存在时间为5分钟
        cookie.setPath("/");//设置作用域
        response.addCookie(cookie);//将cookie添加到response的cookie数组中返回给客户端
    }
    //删除cookie
    public void delCookie(HttpServletRequest request, HttpServletResponse response, String userName){
        Cookie[] cookies = request.getCookies();
        if (null==cookies) {
            System.out.println("没有cookie");
        } else {
            for(Cookie cookie : cookies){
                //如果找到同名cookie，就将value设置为null，将存活时间设置为0，再替换掉原cookie，这样就相当于删除了。
                if(cookie.getName().equals("userName")){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break;
                }
            }
        }
    }
}
